from datetime import datetime, timedelta
from chinese_calendar import is_workday

# 设置开始和结束日期
start_date = datetime.now().date()
end_date = datetime(2025, 3, 31).date()
    
def generate_workday_table():
    # 存储每周数据的二维列表
    calendar = []
    current_week = []
    current_date = start_date

    # 按天递减处理日期
    while current_date >= end_date:
        # 获取当前日期是星期几（0=周一，6=周日）
        weekday = current_date.weekday()

        # 如果是周日或者是处理的第一天，初始化新的一周
        if weekday == 6 or not current_week:
            if current_week:  # 如果不是第一周，添加到日历
                calendar.append(current_week)
            current_week = [None] * 7  # 初始化新的一周

        # 如果是工作日，添加到当前周的对应位置
        if is_workday(datetime.combine(current_date, datetime.min.time())):
            current_week[weekday] = f"{current_date.month}.{current_date.day}"

        # 处理前一天
        current_date -= timedelta(days=1)

    # 添加最后一周
    if current_week:
        calendar.append(current_week)

    # 反转日历以按时间顺序显示
    calendar.reverse()
    return calendar


def print_workday_table(calendar):
    # 表头使用缩写，每个单元格宽度为5个字符
    headers = ["一", "二", "三", "四", "五", "六", "日"]
    print(" ".join(f"{h:^5}" for h in headers))
    print("-" * (7 * 7 - 3))  # 分隔线

    # 打印每一行
    for week in calendar:
        # 格式化每一天，空值显示为空格，宽度5个字符
        formatted_days = [f"{day:^5}" if day else "     " for day in week]
        print("  ".join(formatted_days))


if __name__ == "__main__":
    calendar = generate_workday_table()
    print(f"\n\n从2025年3月31日到{start_date.year}年{int(start_date.month)}月{int(start_date.day)}日（今天）的工作日日历：")
    print_workday_table(calendar)

    # 计算总工作日
    total_workdays = sum(1 for week in calendar for day in week if day is not None)
    print(f"\n总共{total_workdays}个工作日")
